package com.toman.ui.work.device;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.DeviceRepairRecordEntity;
import com.toman.R;
import com.toman.Util.JsonUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.ProgressDialogUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.camera.Camera;
import com.toman.toolbar.ToolBarActivity;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DeviceRepairEditActivity extends ToolBarActivity {

    @BindView(R.id.iv_device)
    ImageView ivDevice;
    @BindView(R.id.rl_device)
    RelativeLayout rlDevice;
    @BindView(R.id.tv_device_dep)
    TextView tvDeviceDep;
    @BindView(R.id.rl_device_dep)
    RelativeLayout rlDeviceDep;
    @BindView(R.id.tv_device_beltline)
    TextView tvDeviceBeltline;
    @BindView(R.id.rl_device_beltline)
    RelativeLayout rlDeviceBeltline;
    @BindView(R.id.tv_device)
    TextView tvDevice;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.tv_mt_code)
    TextView tvMtCode;
    @BindView(R.id.ll_device_more)
    LinearLayout llDeviceMore;
    @BindView(R.id.ll_device)
    LinearLayout llDevice;
    @BindView(R.id.iv_submit)
    ImageView ivSubmit;
    @BindView(R.id.rl_submit)
    RelativeLayout rlSubmit;
    @BindView(R.id.tv_submit_code)
    TextView tvSubmitCode;
    @BindView(R.id.tv_problem)
    TextView tvProblem;
    @BindView(R.id.tv_submit_man)
    TextView tvSubmitMan;
    @BindView(R.id.tv_submit_time)
    TextView tvSubmitTime;
    @BindView(R.id.tv_summit_detail)
    TextView tvSummitDetail;
    @BindView(R.id.et_submit_detail)
    EditText etSubmitDetail;
    @BindView(R.id.tv_sumbmit_remark_name)
    TextView tvSumbmitRemarkName;
    @BindView(R.id.et_submit_remark)
    EditText etSubmitRemark;
    @BindView(R.id.ll_submit_more)
    LinearLayout llSubmitMore;
    @BindView(R.id.ll_submit)
    LinearLayout llSubmit;
    @BindView(R.id.iv_repair)
    ImageView ivRepair;
    @BindView(R.id.rl_repair)
    RelativeLayout rlRepair;
    @BindView(R.id.tv_repair_man)
    TextView tvRepairMan;
    @BindView(R.id.tv_repair_submit_man)
    TextView tvRepairSubmitMan;
    @BindView(R.id.tv_repair_start_time)
    TextView tvRepairStartTime;
    @BindView(R.id.tv_repair_end_time)
    TextView tvRepairEndTime;
    @BindView(R.id.tv_repair_detail_title)
    TextView tvRepairDetailTitle;
    @BindView(R.id.et_repair_detail)
    EditText etRepairDetail;
    @BindView(R.id.ll_repair_more)
    LinearLayout llRepairMore;
    @BindView(R.id.ll_repair)
    LinearLayout llRepair;
    @BindView(R.id.tv_check_man)
    TextView tvCheckMan;
    @BindView(R.id.tv_check_time)
    TextView tvCheckTime;
    @BindView(R.id.ll_check)
    LinearLayout llCheck;
    @BindView(R.id.btn_ok)
    Button btnOk;
    @BindView(R.id.ll_base)
    LinearLayout llBase;
    boolean expand_device = true;
    boolean expand_submit = true;
    boolean expand_repair = true;
    Camera camera;
    String status;
    DeviceRepairRecordEntity bean;
    List<ItemListBean> listSelect = new ArrayList<ItemListBean>();
    List<ItemListBean> list = new ArrayList<ItemListBean>();

    ItemListAdapter adapter, adapter2;
    String repairId;
    String repairSubmitId;
    ListView lvSelect;
    String problemItemId = "";
    Dialog dialog;
    @BindView(R.id.tv_repair_time)
    TextView tvRepairTime;
    @BindView(R.id.tv_act_time)
    TextView tvActTime;
    @BindView(R.id.rl_repair_time)
    RelativeLayout rlRepairTime;
    @BindView(R.id.rl_act)
    RelativeLayout rlAct;
    @BindView(R.id.tv_device_title)
    TextView tvDeviceTitle;
    @BindView(R.id.tv_problem_title)
    TextView tvProblemTitle;
    @BindView(R.id.tv_repair_man_title)
    TextView tvRepairManTitle;
    @BindView(R.id.tv_repair_start_time_title)
    TextView tvRepairStartTimeTitle;
    @BindView(R.id.tv_repair_end_time_title)
    TextView tvRepairEndTimeTitle;
boolean finish=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_repair_edit);
        ButterKnife.bind(this);
        initView();
        initToolBar("设备报修维修");
        initHandler();
    }

    private void initView() {
        adapter = new ItemListAdapter(this);

        adapter2 = new ItemListAdapter(this, 2);

        status = getIntent().getStringExtra("status");
        bean = (DeviceRepairRecordEntity) getIntent().getSerializableExtra("bean");
        tvDeviceDep.setText(bean.getDeviceEntity().getDepartmentEntity().getDepartmentName());
        tvDeviceBeltline.setText(bean.getDeviceEntity().getBeltlineName());
        tvDevice.setText(bean.getDeviceEntity().getDeviceName());
        tvCode.setText(bean.getDeviceEntity().getDeviceCode());
        tvMtCode.setText(bean.getDeviceEntity().getEquipmentCode());
        tvSubmitCode.setText(bean.getId());
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < bean.getProblemItemEntities().size(); i++) {
            if (stringBuilder.length() <= 0) {
                stringBuilder.append(bean.getProblemItemEntities().get(i).getItemName());
            } else {
                stringBuilder.append("、").append(bean.getProblemItemEntities().get(i).getItemName());

            }
        }
        tvProblem.setText(stringBuilder.toString());
        problemItemId = bean.getProblemItemIds();
        tvSubmitMan.setText(bean.getCreateUser().getRealName());
        tvSubmitTime.setText(bean.getCreateTime());
        etSubmitRemark.setText(bean.getRemark());
        etSubmitDetail.setText(bean.getErrorDetail());
        ArrayList<String> list_submit = new ArrayList<>();
        ArrayList<String> list_repair = new ArrayList<>();

        for (int i = 1; i <= 9; i++) {
            Class<? extends DeviceRepairRecordEntity> beanClass = bean.getClass();
            String fieldNamePrefix = "image${index}Path";
            try {
                Field declaredField = beanClass.getDeclaredField(fieldNamePrefix.replace("${index}", i + ""));
                if (declaredField != null) {
                    declaredField.setAccessible(true);
                    Object value = declaredField.get(bean);
                    if (value != null && value != "") {
                        list_submit.add(value.toString());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        for (int i = 1; i <= 9; i++) {
            Class<? extends DeviceRepairRecordEntity> beanClass = bean.getClass();
            String fieldNamePrefix = "image${index}PathRepair";
            try {
                Field declaredField = beanClass.getDeclaredField(fieldNamePrefix.replace("${index}", i + ""));
                if (declaredField != null) {
                    declaredField.setAccessible(true);
                    Object value = declaredField.get(bean);
                    if (value != null && value != "") {
                        list_repair.add(value.toString());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String[] urlSubmit = new String[list_submit.size()];
        list_submit.toArray(urlSubmit);
        String[] urlRepair = new String[list_repair.size()];
        list_repair.toArray(urlRepair);
//        待维修
        if (status.equals("0")) {
            llCheck.setVisibility(View.GONE);
            llRepair.setVisibility(View.GONE);
            btnOk.setVisibility(View.GONE);
            ViewUtil.unclick(tvProblem);
            ViewUtil.unedit(etSubmitDetail, etSubmitRemark);
            camera = ViewUtil.createPhoto("报修图片", urlSubmit, camera, this, llSubmitMore, true);
        }
//        待审核
        if (status.equals("1")) {
            llCheck.setVisibility(View.GONE);
            ViewUtil.unclick(tvProblem, tvRepairMan, tvRepairStartTime, tvRepairEndTime);
            ViewUtil.unedit(etSubmitDetail, etSubmitRemark, etRepairDetail);
            btnOk.setText("审核");
            if (!PermissonUtils.contains(this, BaseEnum.REPAIR.has(PermEnum.CHECK))) {
                btnOk.setVisibility(View.GONE);
            }
            ViewUtil.createPhoto("报修图片", urlSubmit, camera, this, llSubmitMore, true);
            etRepairDetail.setText(bean.getRepairDetail());
//            响应时间维修时间时长
            tvActTime.setText(bean.getResponseDuringTime());
            tvRepairTime.setText(bean.getRepairDuringTime());
            try {
                tvRepairMan.setText(bean.getRepairUser().getRealName());
                tvRepairSubmitMan.setText(bean.getWriteRepairDetailUser().getRealName());
                repairId = bean.getRepairUser().getUserId();
                repairSubmitId = bean.getWriteRepairDetailUser().getUserId();
                tvRepairStartTime.setText(bean.getRepairStartTime());
                tvRepairEndTime.setText(bean.getRepairEndTime());
            } catch (Exception e) {
                e.printStackTrace();
            }
            camera = ViewUtil.createPhoto("维修图片", urlRepair, camera, this, llRepairMore, true);

        }
//        已审核详情
        if (status.equals("2")) {
            ViewUtil.done(tvProblem, tvRepairMan, tvRepairStartTime, tvRepairEndTime);
            ViewUtil.unedit(etSubmitDetail, etSubmitRemark, etRepairDetail);
            btnOk.setVisibility(View.GONE);
            ViewUtil.createPhoto("报修图片", urlSubmit, camera, this, llSubmitMore, true);
            etRepairDetail.setText(bean.getRepairDetail());
            tvRepairMan.setText(bean.getRepairUser().getRealName());
            tvRepairSubmitMan.setText(bean.getWriteRepairDetailUser().getRealName());
//            响应时间维修时间时长
            tvActTime.setText(bean.getResponseDuringTime());
            tvRepairTime.setText(bean.getRepairDuringTime());
            tvRepairStartTime.setText(bean.getRepairStartTime());
            tvRepairEndTime.setText(bean.getRepairEndTime());
            camera = ViewUtil.createPhoto("维修图片", urlRepair, camera, this, llRepairMore, true);
            tvCheckMan.setText(bean.getAuditUser().getRealName());
            tvCheckTime.setText(bean.getAuditTime());
        }
//        维修
        if (status.equals("3")) {
            llCheck.setVisibility(View.GONE);
            ViewUtil.click(tvProblem, tvRepairMan, tvRepairStartTime, tvRepairEndTime);
            ViewUtil.edit(etRepairDetail);
            ViewUtil.unedit(etSubmitRemark, etSubmitDetail);
            ViewUtil.gone(rlAct, rlRepairTime);
            ViewUtil.necessary(tvProblemTitle,tvRepairManTitle,tvRepairStartTimeTitle,tvRepairEndTimeTitle,tvRepairDetailTitle);
            btnOk.setText("维修");

            ViewUtil.createPhoto("报修图片", urlSubmit, camera, this, llSubmitMore, true);
            etRepairDetail.setText(bean.getRepairDetail());
            tvRepairMan.setText((String) SPUtils.get(getApplicationContext(), "username", ""));
            tvRepairSubmitMan.setText((String) SPUtils.get(getApplicationContext(), "username", ""));
            repairId = (String) SPUtils.get(getApplicationContext(), "userid", "");
            repairSubmitId = (String) SPUtils.get(getApplicationContext(), "userid", "");

            camera = ViewUtil.createPhoto("维修图片", urlRepair, camera, this, llRepairMore, false);
        }
    }

    private void initHandler() {
        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {

                    case 1:
                        dialog.dismiss();
                        ToastUtil.makeText(getApplicationContext(), (String) msg.obj);
                        finish();
                        break;
                    case 2:
                        dialog.dismiss();
                        ToastUtil.makeText(getApplicationContext(), (String) msg.obj);

                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_edit, menu);


        MenuItem menuItem = menu.findItem(R.id.menu_edit);
        if (status.equals("2") || status.equals("3")) {
            menuItem.setVisible(false);
        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_edit:
                        if (item.getTitle().equals("编辑")) {
                            item.setTitle("完成");
                            switch (status) {
                                case "0":
                                    ViewUtil.edit(etSubmitDetail, etSubmitRemark);
                                    ViewUtil.click(tvProblem);
                                    ViewUtil.necessary(tvSummitDetail,tvProblemTitle);
                                    camera.init(false);
                                    break;

                                case "1":
                                    camera.init(false);
                                    ViewUtil.click(tvProblem, tvRepairMan, tvRepairStartTime, tvRepairEndTime);
                                    ViewUtil.edit(etRepairDetail);
                                    ViewUtil.necessary(tvProblemTitle,tvRepairManTitle,tvRepairEndTimeTitle,tvRepairStartTimeTitle,tvRepairDetailTitle);
                                    break;
                            }
                        } else if(item.getTitle().equals("完成")){
                            switch (status) {
                                case "0":

                                    add();
                                    if (finish) {
                                        item.setTitle("编辑");
                                        ViewUtil.unedit(etSubmitDetail, etSubmitRemark);
                                        ViewUtil.unclick(tvProblem);
                                    }
                                    break;

                                case "1":
                                    ViewUtil.unclick(tvProblem, tvRepairMan, tvRepairStartTime, tvRepairEndTime);
                                    ViewUtil.unedit(etSubmitDetail, etSubmitRemark, etRepairDetail);
//                                    editDialog();
                                    repair();
                                    break;
                            }

                        }
                        break;
                }
                return false;
            }
        });

        return true;
    }

    public void problemDialog() {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        lvSelect = (ListView) textEntryView.findViewById(R.id.lv);
        lvSelect.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
        lvSelect.setAdapter(adapter2);

        builder                //对话框的标题
                .setTitle("选择故障项目")
                //设定显示的View
                .setView(textEntryView)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        SparseBooleanArray array;
                        array = lvSelect.getCheckedItemPositions();
                        StringBuilder names = new StringBuilder();
                        StringBuilder ids = new StringBuilder();
                        for (int i = 0; i < array.size(); i++) {
                            if (array.get(i)) {
                                if (names.length() <= 0) {
                                    names.append(listSelect.get(i).getName());
                                    ids.append(listSelect.get(i).getID());
                                } else {
                                    names.append("、").append(listSelect.get(i).getName());
                                    ids.append(",").append(listSelect.get(i).getID());

                                }
                            }
                        }
                        tvProblem.setText(names.toString());
                        problemItemId = ids.toString();

                    }
                })
                //对话框的“退出”单击事件
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();
        dialog = builder.show();
        getProblemItems();
    }

    public void getProblemItems() {

        OkHttpUtils
                .get(NewBaseUrl.problemitem_list_get)
                .params("token", token)
                .params("companyId", mCompanyId)
                .params("departmentId", getIntent().getStringExtra("id"))
                .params("limit", "1000")
                .params("page", "1")
                .params("status","0")
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "获取故障项目列表: " + result);
                        listSelect.clear();
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());
                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");
                            JSONArray jsonArray = Jpage.getJSONArray("list");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("itemName"), jsonArray.getJSONObject(i).getString("id"));
                                listSelect.add(bean);
                                lvSelect.setItemChecked(i, false);

                            }
                            if (listSelect.size() == 0) {
                                ToastUtil.makeText(getApplicationContext(), "暂无数据，请联系管理员！");
                            }

                            adapter2.refreshData(listSelect);
                            adapter2.notifyDataSetChanged();
                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    public void repairManDialog() {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        ListView lv = (ListView) textEntryView.findViewById(R.id.lv);
        lv.setAdapter(adapter);

        builder                //对话框的标题
                .setTitle("选择维修人员")
                //设定显示的View
                .setView(textEntryView)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        //获取用户输入的“用户名”，“密码”


                    }
                })
                //对话框的“退出”单击事件
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();
        dialog = builder.show();
        repairMan();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean = adapter.getItem(i);
                repairId = bean.getID();
                tvRepairMan.setText(bean.getName());
                dialog.dismiss();
            }
        });

    }

    public void repairMan() {


        OkHttpUtils
                .get(NewBaseUrl.user_repairList)
                .params("token", token)
                .params("companyId", mCompanyId)
                .params("limit", "1000")
                .params("page", "1")
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "维修人员列表: " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());
                        if (code == 0) {
                            list.clear();
                            JSONObject Jpage = jsonObj.getJSONObject("page");
                            JSONArray jsonArray = Jpage.getJSONArray("list");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("realName"), jsonArray.getJSONObject(i).getString("userId"));
                                list.add(bean);
                            }
                            adapter.refreshData(list);

                            adapter.notifyDataSetChanged();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        camera.onActivityResult(requestCode, resultCode, data);
    }


    @OnClick({R.id.rl_device, R.id.rl_submit, R.id.tv_problem, R.id.rl_repair, R.id.tv_repair_man, R.id.tv_repair_start_time, R.id.tv_repair_end_time, R.id.btn_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_device:
                if (expand_device) {
                    llDeviceMore.setVisibility(View.GONE);
                    ivDevice.setImageResource(R.mipmap.down);
                } else {
                    llDeviceMore.setVisibility(View.VISIBLE);
                    ivDevice.setImageResource(R.mipmap.upward);

                }
                expand_device = !expand_device;
                break;
            case R.id.rl_submit:
                if (expand_submit) {
                    llSubmitMore.setVisibility(View.GONE);
                    ivSubmit.setImageResource(R.mipmap.down);
                } else {

                    llSubmitMore.setVisibility(View.VISIBLE);
                    ivSubmit.setImageResource(R.mipmap.upward);

                }
                expand_submit = !expand_submit;

                break;
            case R.id.tv_problem:
                problemDialog();
                break;
            case R.id.rl_repair:
                if (expand_repair) {
                    llRepairMore.setVisibility(View.GONE);
                    ivRepair.setImageResource(R.mipmap.down);
                } else {

                    llRepairMore.setVisibility(View.VISIBLE);
                    ivRepair.setImageResource(R.mipmap.upward);

                }
                expand_repair = !expand_repair;

                break;
            case R.id.tv_repair_man:
                repairManDialog();
                break;
            case R.id.tv_repair_start_time:
                ViewUtil.getDateTimeNo(this, tvRepairStartTime);
                break;
            case R.id.tv_repair_end_time:
                ViewUtil.getDateTimeNo(this, tvRepairEndTime);

                break;
            case R.id.btn_ok:
                if (btnOk.getText().toString().equals("维修")) {
                    repairDialog();
                }
                if (btnOk.getText().toString().equals("审核")) {
                    checkDialog();
                }
                break;
        }
    }

    public void add() {
        finish=false;

        if (problemItemId.equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择故障项目");
            return;
        }
        if (etSubmitDetail.getText().toString().equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请输入故障详细信息");
            return;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < camera.getDeleteUrl().size(); i++) {
            if (stringBuilder.length() <= 0) {
                stringBuilder.append(camera.getDeleteUrl().get(i));
            } else {
                stringBuilder.append(",").append(camera.getDeleteUrl().get(i));
            }
        }
        finish=true;

        List<String> list = camera.getCompressUrl();
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", bean.getId());
        map.put("remark", etSubmitRemark.getText().toString());
        map.put("errorDetail", etSubmitDetail.getText().toString());
        map.put("problemItemIds", problemItemId);
        map.put("token", token);
        map.put("deleteUrls", stringBuilder.toString());
        submit((HashMap<String, String>) map, list);
    }

    public void repair() {
        finish=false;
        if (tvRepairStartTime.getText().toString().equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择维修开始时间");
            return;

        }
        if (tvRepairEndTime.getText().toString().equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择维修结束时间");
            return;
        }
        if (!TimeUtil.compareTwoTime2(tvRepairStartTime.getText().toString(), tvRepairEndTime.getText().toString())) {
            ToastUtil.makeText(getApplicationContext(), "结束时间必须晚于开始时间");
            return;
        }


        if (etRepairDetail.getText().toString().equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请输入维修详细信息");
            return;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < camera.getDeleteUrl().size(); i++) {
            if (stringBuilder.length() <= 0) {
                stringBuilder.append(camera.getDeleteUrl().get(i));
            } else {
                stringBuilder.append(",").append(camera.getDeleteUrl().get(i));
            }
        }
        finish=true;

        List<String> list = camera.getCompressUrl();
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", bean.getId());
        map.put("repairStartTime", tvRepairStartTime.getText().toString());
        map.put("repairEndTime", tvRepairEndTime.getText().toString());
        map.put("repairDetail", etRepairDetail.getText().toString());
        map.put("problemItemIds", problemItemId);
        map.put("repairUserId", repairId);
        map.put("token", token);
        map.put("deleteUrls", stringBuilder.toString());

        for (String key : map.keySet()) {
            System.out.println(key + "/" + map.get(key));
        }
        repairSend((HashMap<String, String>) map, list);
    }

    private void submit(HashMap<String, String> map, List<String> paths) {
        dialog = ProgressDialogUtils.showProgressDialog(this, "正在上传中", "请稍后");

        final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        //创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS).build();
        MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);

//遍历map中所有参数到builder
        for (String key : map.keySet()) {
            mbody.addFormDataPart(key, map.get(key));
        }


        for (String path : paths) {
            File file = new File(path);
            if (file.exists()) {
                mbody.addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
            }
            // builder.addFormDataPart("file[]", null, RequestBody.create(MEDIA_TYPE_PNG, new File(path)));
        }


        //构建请求体
        RequestBody requestBody = mbody.build();
        final Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + "...")

                .url(NewBaseUrl.devicerepairrecord_update)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                dialog.dismiss();

                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();

                Log.i("修改报修", result);
                JSONObject jsonObj = JSON.parseObject(result);
                int code = jsonObj.getInteger("code");
                ViewUtil.lagout(code, getApplicationContext());
                if (code == 0) {
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = jsonObj.getString("msg");//可以是基本类型，可以是对象，可以是List、map等；
                    mHandler.sendMessage(msg);
                } else {
                    ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                    Message msg = new Message();
                    msg.what = 2;
                    msg.obj = jsonObj.getString("msg");//可以是基本类型，可以是对象，可以是List、map等；
                    mHandler.sendMessage(msg);
                }
            }
        });

    }

    private void repairSend(HashMap<String, String> map, List<String> paths) {
        dialog = ProgressDialogUtils.showProgressDialog(this, "正在上传中", "请稍后");
        final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        //创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS).build();
        MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);

//遍历map中所有参数到builder
        for (String key : map.keySet()) {
            mbody.addFormDataPart(key, map.get(key));
        }


        for (String path : paths) {
            File file = new File(path);
            if (file.exists()) {
                mbody.addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
            }
            // builder.addFormDataPart("file[]", null, RequestBody.create(MEDIA_TYPE_PNG, new File(path)));
        }


        //构建请求体
        RequestBody requestBody = mbody.build();
        final Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + "...")

                .url(NewBaseUrl.devicerepairrecord_repair)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                dialog.dismiss();

                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();

                Log.i("维修", result);
                JSONObject jsonObj = JSON.parseObject(result);
                int code = jsonObj.getInteger("code");
                ViewUtil.lagout(code, getApplicationContext());
                if (code == 0) {
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = jsonObj.getString("msg");//可以是基本类型，可以是对象，可以是List、map等；
                    mHandler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.what = 2;
                    msg.obj = jsonObj.getString("msg");//可以是基本类型，可以是对象，可以是List、map等；
                    mHandler.sendMessage(msg);
                }
            }
        });
    }

    public void checkDialog() {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("确认审核当条维修记录？")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        check();
                    }

                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }

    public void repairDialog() {
        if (tvRepairStartTime.getText().toString().equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择维修开始时间");
            return;

        }
        if (tvRepairEndTime.getText().toString().equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择维修结束时间");
            return;
        }
        if (!TimeUtil.compareTwoTime2(tvRepairStartTime.getText().toString(), tvRepairEndTime.getText().toString())) {
            ToastUtil.makeText(getApplicationContext(), "结束时间必须晚于开始时间");
            return;
        }


        if (etRepairDetail.getText().toString().equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请输入维修详细信息");
            return;
        }
        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("确认要进行维修？")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        repair();
                    }

                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }

    public void editDialog() {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("确认要进行修改？")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        repair();
                    }

                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }

    private void check() {


        Map<String, String> map = new HashMap<String, String>();

        map.put("ids", bean.getId());

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.devicerepairrecord_verify + bean.getId())
                .headers("token", token)
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "审核保修维修: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }
}
